/*
'  DotNetNuke -  http://www.dotnetnuke.com
'  Copyright (c) 2002-2011
'  by DotNetNuke Corporation
' 
'  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
'  documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
'  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
'  to permit persons to whom the Software is furnished to do so, subject to the following conditions:
' 
'  The above copyright notice and this permission notice shall be included in all copies or substantial portions 
'  of the Software.
' 
'  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
'  TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
'  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
'  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
'  DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Lists;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Security.Roles;
using DotNetNuke.UI.WebControls;
using DotNetNuke.UI.UserControls;
using DotNetNuke.Modules.Store.Providers;
using DotNetNuke.Modules.Store.Providers.Address;
using DotNetNuke.Modules.Store.Admin;

namespace DotNetNuke.Modules.Store.Providers.Address.DefaultAddressProvider
{
	/// <summary>
	/// Summary description for CoreProfile.
	/// </summary>
	public partial class DefaultAddressCheckout : AddressCheckoutControlBase
	{
		#region Private Declarations

		private bool _shippingAddressSelectionVisible = true;
        private string _addressDefaultDescription;

        #endregion

		#region Web Form Designer generated code

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

        }

		#endregion

		#region Event Handlers
        
		protected void Page_Load(object sender, System.EventArgs e)
		{
            if (IsPostBack == false)
            {
                IAddressInfo billingAddress = addressBilling.AddressInfo;
                if (billingAddress != null)
                {
                    int billingAddressID = billingAddress.AddressID;
                    IAddressInfo shippingAddress = addressShipping.AddressInfo;
                    int shippingAddressID = shippingAddress.AddressID;

                    if (IsLogged == true)
                    {
                        // Get default address description
                        _addressDefaultDescription = Localization.GetString("AddressDefaultDescription", this.LocalResourceFile);

                        //Get the user's addresses
                        AddressController controller = new AddressController();
                        List<AddressInfo> addresses = controller.GetAddresses<AddressInfo>(PortalId, UserId, _addressDefaultDescription);

                        // Bind addresses lists
                        lstBillAddress.DataSource = addresses;
                        lstBillAddress.DataTextField = "Description";
                        lstBillAddress.DataValueField = "AddressID";
                        lstBillAddress.DataBind();
                        lstBillAddress.Items.Insert(0, new ListItem(Localization.GetString("SelectBillingAddress", this.LocalResourceFile), "-1"));

                        lstShipAddress.DataSource = addresses;
                        lstShipAddress.DataTextField = "Description";
                        lstShipAddress.DataValueField = "AddressID";
                        lstShipAddress.DataBind();
                        lstShipAddress.Items.Insert(0, new ListItem(Localization.GetString("SelectShippingAddress", this.LocalResourceFile), "-1"));

                        // If billing address is not set
                        if (billingAddressID == Null.NullInteger)
                        {
                            int AddressIndex = 1; // Default to registration address
                            // Search for the primary address
                            if (addresses.Count > 1)
                            {
                                int Index = 1;
                                foreach (IAddressInfo address in addresses)
                                {
                                    if (address.PrimaryAddress)
                                    {
                                        AddressIndex = Index;
                                        billingAddress = address;
                                        break;
                                    }
                                    Index++;
                                }
                            }
                            // Define selected addresses
                            billingAddressID = billingAddress.AddressID;
                            addressBilling.AddressInfo = billingAddress;
                            this.SendBillingAddressChangedEvent();
                        }
                        if (shippingAddressID != Null.NullInteger && shippingAddressID != billingAddressID)
                        {
                            if (shippingAddressID > 0)
                                lstShipAddress.SelectedIndex = addresses.IndexOf((AddressInfo)shippingAddress) + 1;
                            radShipping.Checked = true;
                            rowListShipAddress.Visible = true;
                            ShippingAddressSelectionVisible = true;
                        }
                        else
                        {
                            radBilling.Checked = true;
                            rowListShipAddress.Visible = false;
                            ShippingAddressSelectionVisible = false;
                        }
                    }
                    else
                    {
                        rowListBillAddress.Visible = false;
                        rowListShipAddress.Visible = false;
                        if (shippingAddressID != Null.NullInteger && shippingAddressID != billingAddressID)
                        {
                            radShipping.Checked = true;
                            ShippingAddressSelectionVisible = true;
                        }
                        else
                        {
                            radBilling.Checked = true;
                            ShippingAddressSelectionVisible = false;
                        }
                    }

                    // Update interface
                    UpdateBillingInterface();
                    UpdateShippingInterface();
                }
            }
        }

		protected void lstBillAddress_SelectedIndexChanged(object sender, System.EventArgs e)
		{
            loadBillAddress(int.Parse(lstBillAddress.SelectedValue));
            this.SendBillingAddressChangedEvent();
            UpdateBillingInterface();
		}

		protected void lstShipAddress_SelectedIndexChanged(object sender, System.EventArgs e)
		{
            loadShipAddress(int.Parse(lstShipAddress.SelectedValue));
            this.SendShippingAddressChangedEvent();
            UpdateShippingInterface();
		}

		protected void radNone_CheckedChanged(object sender, System.EventArgs e)
		{
			if (radNone.Checked)
			{
                lstShipAddress.SelectedIndex = 0;
                loadShipAddress(int.Parse(lstShipAddress.SelectedValue));
                this.SendShippingAddressChangedEvent();
				ShippingAddressSelectionVisible = false;
			}
		}

		protected void radBilling_CheckedChanged(object sender, System.EventArgs e)
		{
			if (radBilling.Checked == true)
			{
                if (IsLogged == true)
                {
                    lstShipAddress.SelectedIndex = 0;
                    loadShipAddress(int.Parse(lstShipAddress.SelectedValue));
                }
                else
                    loadShipAddress(Null.NullInteger);
                this.SendShippingAddressChangedEvent();
				ShippingAddressSelectionVisible = false;
			}
		}

		protected void radShipping_CheckedChanged(object sender, System.EventArgs e)
		{
			if (radShipping.Checked == true)
				ShippingAddressSelectionVisible = true;
		}

		#endregion

		#region Private Functions

        private void UpdateBillingInterface()
        {
            // Update billing interface
            IAddressInfo billingAddress = addressBilling.AddressInfo;
            int billingAddressID = billingAddress.AddressID;

            if (billingAddressID > 0)
            {
                if (IsLogged == true)
                {
                    lstBillAddress.ClearSelection();
                    ListItem item = lstBillAddress.Items.FindByValue(billingAddressID.ToString());
                    if (item != null)
                    {
                        item.Selected = true;
                        addressBilling.ShowUserSaved = false;
                        addressBilling.ShowPrimary = false;
                        addressBilling.ShowDescription = false;
                    }
                    else
                        addressBilling.ShowUserSaved = true;
                }
            }
            else
            {
                if (IsLogged == true)
                    addressBilling.ShowUserSaved = true;
            }
            addressBilling.PopulateAddress();
        }

        private void UpdateShippingInterface()
        {
            // Update shipping interface
            IAddressInfo shippingAddress = addressShipping.AddressInfo;
            int shippingAddressID = shippingAddress.AddressID;

            if (shippingAddressID > 0)
            {
                if (IsLogged == true)
                {
                    lstShipAddress.ClearSelection();
                    ListItem item = lstShipAddress.Items.FindByValue(shippingAddressID.ToString());
                    if (item != null)
                    {
                        item.Selected = true;
                        addressShipping.ShowUserSaved = false;
                        addressShipping.ShowPrimary = false;
                        addressShipping.ShowDescription = false;
                    }
                    else
                        addressShipping.ShowUserSaved = true;
                }
            }
            else
            {
                if (IsLogged == true)
                    addressShipping.ShowUserSaved = true;
            }
            addressShipping.PopulateAddress();
        }

		/// <summary>
		/// Retrieve an IAddressInfo from the address controller using 
		/// the address id.
		/// </summary>
		/// <param name="addressId">Address ID to be loaded.</param>
		/// <returns>A populated IAddressInfo if the address was found; otherwise null</returns>
		private IAddressInfo loadAddress(int addressId)
		{
			AddressController controller = new AddressController();
			if (addressId > 0)
				return controller.GetAddress(addressId);
			else
                return controller.GetRegistrationAddress(PortalId, UserId, _addressDefaultDescription);
		}

		private void loadBillAddress(int addressId)
		{
            IAddressInfo address = null;

			if (addressId != Null.NullInteger)
				address = loadAddress(addressId);

			if (address != null)
			{
                // Get user account email if user is connected and email address is empty
                if (UserId != Null.NullInteger && string.IsNullOrEmpty(address.Email) == true)
                    address.Email = UserInfo.Email;
                addressBilling.AddressInfo = address;
			}
            else
                addressBilling.AddressInfo = new AddressInfo();
		}

		private void loadShipAddress(int addressId)
		{
		    IAddressInfo address = null;

            if (addressId >= 0)
                address = loadAddress(addressId);

            if (address != null)
            {
                // Get user account email if user is connected and email address is empty
                if (UserId != Null.NullInteger && string.IsNullOrEmpty(address.Email) == true)
                    address.Email = UserInfo.Email;
                addressShipping.AddressInfo = address;
            }
            else
                addressShipping.AddressInfo = new AddressInfo();
		}
		
		private bool ShippingAddressSelectionVisible
		{
            get { return _shippingAddressSelectionVisible; }
			set 
			{
				_shippingAddressSelectionVisible = value;
                rowListShipAddress.Visible = value == true ? IsLogged : false;
				addressShipping.Visible = _shippingAddressSelectionVisible;
			}
		}

		#endregion

		#region Public Functions/Properties

		public override IAddressInfo BillingAddress
		{
            get { return addressBilling.AddressInfo; }
			set
            {
                addressBilling.AddressInfo = value;
                UpdateBillingInterface();
            }
		}

		public override IAddressInfo ShippingAddress
		{
            get { return addressShipping.AddressInfo; }
			set
            {
                addressShipping.AddressInfo = value;
                UpdateShippingInterface();
            }
		}

		#endregion
	}
}
